package com.dragon.sdgp.common.security;

import cn.hutool.json.JSONUtil;
import com.dragon.sdgp.common.R;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @AUTHOR : Dragon_Yang
 * @File : LoginFailureHandler
 * @DESCRIPTION : 登录成功处理器
 * @DATE : 2023/2/27 21:14
 */
//@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String msg = e.getMessage();
        if(e instanceof BadCredentialsException){
            msg = "用户名或密码错误";
        }

        outputStream.write(JSONUtil.toJsonStr(R.fail(400, msg)).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
